<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Controller\user;

use App\Dao\GoodsDao;
use App\Dao\UserFavDao;
use App\Middleware\User\UserMiddleware;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;

/**
 * 收藏接口
 *
 * @Middleware(UserMiddleware::class)
 * @AutoController()
 * @author 刘兴永(aile8880@qq.com)
 * @package App\Controller\user
 */
class FavController extends Controller
{
    /**
     * @Inject
     * @var UserFavDao
     */
    public $dao;

    /**
     * @Inject
     * @var GoodsDao
     */
    private $goods_dao;

    /**
     * 商品收藏列表
     */
    public function list()
    {
        $result = $this->dao->get([
            'user_id' => uid()
        ]);

        $this->success($result);
    }

    /**
     * 添加/移出收藏
     */
    public function handle()
    {
        $goods_id = (int)$this->request->input('goods_id', 0);

        // 检测商品是否存在
        if (!$this->goods_dao->existsGoodsById($goods_id)) {
            $this->error('GOODS.NOT_FOUND');
        }

        // 检测该商品是否已经加入收藏，已经加入则删除
        if ($exists = $this->dao->first([
            'user_id' => uid(),
            'goods_id' => $goods_id
        ])) {
            $exists->delete();

            $status = false;
        }
        else {
            $this->dao->create([
                'user_id' => uid(),
                'goods_id' => $goods_id,
                'status' => 1,
                'fav_time' => time()
            ]);

            $status = true;
        }

        $this->success($status);
    }

    /**
     * 删除收藏
     */
    public function del()
    {
        $id = (int)$this->request->input('id', 0);

        $this->dao->delete([
            'user_id' => uid(),
            'id' => $id
        ]);

        $this->success();
    }
}